import axios from 'axios'
import { Message } from '@arco-design/web-vue'
import router from '@/router'


export interface Result<T> {
  code: number
  msg: string
  data: T
}

export interface PageInfo<T> {
  list: T[]
  pageNum: number
  pageSize: number
  total: number
}

//@ts-ignore
export interface BaseObject {
  id: number
  createTime: string
  updateTime: string
  createBy: number
  delBy: number
  del: boolean
  remark: string
}


const axiosInstance = axios.create({
  baseURL: '/api',
  timeout: 6000
})

//前置请求拦截
axiosInstance.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.set('token', token.trim())
  }
  return config
})

//@ts-ignore
axiosInstance.interceptors.response.use(axiosResponse => {

  //请求异常
  if (axiosResponse.status != 200) {
    Message.error('系统错误：请求异常！' + axiosResponse.statusText)
    return Promise.reject('系统错误：请求异常！' + axiosResponse.statusText)
  }

  //请求成功
  const resp = axiosResponse.data as Result<any>

  if (resp.code == 200) {
    //如果非200则表示错误
    return resp
  } else if (resp.code == 401) {
    //未登录，或则登录失效等
    router.replace('/login')
    Message.error(resp.msg)
    return Promise.reject(resp.msg)
  } else {
    Message.error(resp.msg)
    return Promise.reject(resp.data)
  }
}, error => {
  Message.error('网络异常：' + error)
})

export default axiosInstance
